<template>
  <div>
    <el-container>
      <el-header>广告列表</el-header>
      <el-main>
        <el-card>
          <el-form :model="content" class="content-form">
            <el-form-item label="标题">
              <el-input v-model="content.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="类别">
              <el-select v-model="content.categoryId" placeholder="全部类别" style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option v-for="(item, index) in contentCategory" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button plain type="primary" @click="searchContent">搜索</el-button>
              <el-button plain @click="openDialog('添加广告')">添加</el-button>
              <el-button plain @click="toggleSelection">删除</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="tableData" class="content-list" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="广告id" prop="id" />
            <el-table-column label="标题" prop="title" />
            <el-table-column label="路径" prop="url" />
            <el-table-column label="图片" prop="pic" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :background="background"
              :disabled="disabled"
              :page-sizes="[2, 3, 5, 7]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </el-card>

        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
          <el-form :rules="rules" :model="contentInfo">
            <el-form-item label="编号">
              <el-input v-model="contentInfo.id" disabled />
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="contentInfo.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="路径" prop="url">
              <el-input v-model="contentInfo.url" autocomplete="off" />
            </el-form-item>
            <el-form-item label="图片" prop="pic">
              <el-upload action="" :http-request="uploadFile" :before-upload="beforeUpload" list-type="picture-card">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="类别">
              <el-select v-model="contentInfo.categoryId" placeholder="全部类别" style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option v-for="(item, index) in contentCategory" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formSubmitHandler">确定</el-button>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import contentApi from '../http/httpContentRequest.js';
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus';
import axios from 'axios';

const formLabelWidth = ref('100px');
const tableData = ref([]);
const pageSize = ref(3);
const pageNum = ref(1);
const total = ref(20);
const background = ref(false);
const disabled = ref(false);

const content = ref({});
const contentCategory = ref([]);
const contentInfo = ref({});
const dialogFormVisible = ref(false);
const dialogTitle = ref('添加广告');

const multipleSelection = ref([]);
const dialogImagePic = ref('');
const dialogVisible = ref(false);

const rules = {
  title: [{required: true, message: '请输入标题', trigger: 'blur'}],
  url: [{required: true, message: '请输入url', trigger: 'blur'}],
  categoryId: [{required: true, message: '请选择广告类别', trigger: 'blur'}],
};

const searchContent = async () => {
  const searchUrl = `/content/search/${pageNum.value}/${pageSize.value}`;
  const result = await contentApi.doPost(searchUrl, content.value);
  tableData.value = result.data.pr.rows;
  total.value = result.data.pr.total;
};

const contentCategoryList = async () => {
  const result = await contentApi.doGet('/contentCategory/list');
  contentCategory.value = result.data.list;
};

const handleCurrentChange = (num) => {
  pageNum.value = num;
  searchContent();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  searchContent();
};

const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  dialogTitle.value = '编辑广告';
  contentInfo.value = {...row};
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleDelete = async (index, row) => {
  const ids = row ? [row.id] : multipleSelection.value.map((row) => row.id).join(',');
  await contentApi.doDelete(`/content/delete/${ids}`);
  ElMessage.success('删除成功');
  searchContent();
};

const formSubmitHandler = async () => {
  let result;
  ElMessageBox.confirm(`确认${dialogTitle.value}吗`).then(async () => {
    if (dialogTitle.value === '添加广告') {
      result = await contentApi.doPost('/content/add', contentInfo.value);
    } else {
      contentInfo.value.pic = dialogImagePic.value;
      result = await contentApi.doPost('/content/update', contentInfo.value);
    }
    ElNotification({message: result.message, type: result.code === 200 ? 'success' : 'error'});
    await searchContent();
  }).catch(() => {
    ElMessage.info('取消');
  });
  dialogFormVisible.value = false;
};

const uploadFile = async ({file, onProgress, onSuccess, onError}) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await axios.post('/hzit/content/upload', formData, {
      headers: {'Content-Type': 'multipart/form-data'},
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress({percent: percentCompleted}, file);
      },
    });
    onSuccess(response.data);
    dialogImagePic.value = response.data.pic;
    dialogVisible.value = true;
  } catch (error) {
    onError(error);
  }
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('上传文件只能是图片!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

const handlePictureCardPreview = (file) => {
  dialogImagePic.value = file.pic;
  dialogVisible.value = true;
};

onMounted(() => {
  contentCategoryList();
  searchContent();
});
</script>

<style scoped>
/* 样式保持原样，已优化代码部分 */
</style>
